import { types } from "recast";

const { ifStatement, blockStatement, expressionStatement, unaryExpression } =
  types.builders;

/**
 * 获取所有表达式陈述语句，如果该表达式为逻辑表达式，那么转化为If语句
 */
const modifyLogicalExpression = function (path) {
  if (path.node.expression.operator == "&&") {
    const newStatement = ifStatement(
      path.node.expression.left,
      blockStatement([expressionStatement(path.node.expression.right)])
    );
    const parentPath = path.insertBefore(newStatement);
    path.prune();
    parentPath.each((childPath) => {
      if (newStatement === childPath.node) {
        this.visit(childPath);
      }
    });
  } else if (path.node.expression.operator == "||") {
    const newStatement = ifStatement(
      unaryExpression("!", path.node.expression.left, true),
      blockStatement([expressionStatement(path.node.expression.right)])
    );
    const parentPath = path.insertBefore(newStatement);
    path.prune();
    parentPath.each((childPath) => {
      if (newStatement === childPath.node) {
        this.visit(childPath);
      }
    });
  }
};

export default modifyLogicalExpression;
